﻿namespace Groundwork.Core
{
    using System;
    using System.IO;
    using System.Runtime.InteropServices;

    /// <summary>
    /// Creates an instance of the ConsoleText class
    /// </summary>
    public class ConsoleText : IDisposable
    {
        [DllImport("Kernel32.dll")]
        private static extern bool AttachConsole(int processId);

        [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
        private static extern bool FreeConsole();

        /// <summary>
        /// Allows you to write messages to the command console.
        /// </summary>
        public ConsoleText()
        {
            AttatchToConsole();
        }

        /// <summary>
        /// Writes the specified message to the console window
        /// </summary>
        /// <param name="message">message to display</param>
        public void Write(string message)
        {
            Console.WriteLine(message);
        }

        public void AttatchToConsole(int processId = -1)
        {
            AttachConsole(processId);
            StreamWriter standardOutput = new StreamWriter(Console.OpenStandardOutput());
            standardOutput.AutoFlush = true;
            Console.SetOut(standardOutput);
        }

        public void ReleaseConsole()
        {
            FreeConsole();
        }

        public void Dispose()
        {
            ReleaseConsole();
        }
    }
}
